import joblib
import json
import sys
import pandas as pd
from sklearn.preprocessing import OneHotEncoder

# 加载模型和特征名称
model = joblib.load('model/best_house_price_predictor.pkl')
feature_names = joblib.load('model/feature_names.pkl')

def process_data(input_data):
    # 将输入数据转为DataFrame
    df = pd.DataFrame([input_data])
    
    # 分类字段定义（需与训练时一致）
    categorical_cols = ['orientation', 'decoration', 'floor', 'buildingStructure']
    
    # 加载训练时的编码器
    encoder = OneHotEncoder(handle_unknown='ignore')
    encoder.fit(pd.DataFrame({col: feature_names[col] for col in categorical_cols}))  # 使用保存的特征名称
    
    # 对分类字段进行编码
    encoded = encoder.transform(df[categorical_cols]).toarray()
    encoded_df = pd.DataFrame(encoded, columns=encoder.get_feature_names_out())
    
    # 合并数值型和分类特征
    numeric_df = df.drop(columns=categorical_cols)
    final_df = pd.concat([numeric_df, encoded_df], axis=1)
    
    # 确保列顺序与训练时一致
    return final_df[feature_names['all']]

if __name__ == "__main__":
    data_str = sys.argv[1]
    input_data = json.loads(data_str)
    
    try:
        processed_data = process_data(input_data)
        prediction = model.predict(processed_data)
        print(round(prediction[0], 2))
    except Exception as e:
        print(f"ERROR: {str(e)}")
        sys.exit(1)